package io.renren.modules.doc.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.doc.entity.ChatHistoryEntity;
import io.renren.modules.doc.service.ChatHistoryService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 对话管理
 */
@RestController
@RequestMapping("/doc/chat")
public class ChatController {
    @Autowired
    private ChatHistoryService chatHistoryService;

    /**
     * 聊天历史列表
     */
    @GetMapping("/list")
    @RequiresPermissions("doc:chat:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = chatHistoryService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 获取会话历史记录
     */
    @GetMapping("/history/{sessionId}")
    @RequiresPermissions("doc:chat:list")
    public R history(@PathVariable("sessionId") String sessionId){
        if (sessionId == null || sessionId.trim().isEmpty()) {
            return R.error("会话ID不能为空");
        }
        List<ChatHistoryEntity> list = chatHistoryService.getSessionHistory(sessionId);
        return R.ok().put("list", list);
    }

    /**
     * 获取用户会话列表
     */
    @GetMapping("/sessions/{userId}")
    @RequiresPermissions("doc:chat:list")
    public R sessions(@PathVariable("userId") Long userId){
        if (userId == null || userId <= 0) {
            return R.error("用户ID不合法");
        }
        List<Map<String, Object>> sessions = chatHistoryService.getUserSessions(userId);
        return R.ok().put("sessions", sessions);
    }

    /**
     * 查找相似对话
     */
    @PostMapping("/similar")
    @RequiresPermissions("doc:chat:list")
    public R findSimilar(@RequestParam("vector") Double[] vectorEmbedding,
                        @RequestParam(value = "threshold", defaultValue = "0.8") double threshold,
                        @RequestParam(value = "limit", defaultValue = "10") int limit){
        List<ChatHistoryEntity> list = chatHistoryService.findSimilarChats(vectorEmbedding, threshold, limit);
        return R.ok().put("list", list);
    }

    /**
     * 保存聊天记录
     */
    @PostMapping("/save")
    @RequiresPermissions("doc:chat:save")
    public R save(@RequestBody ChatHistoryEntity chatHistory){
        if (chatHistory == null || chatHistory.getSessionId() == null || 
            chatHistory.getMessage() == null || chatHistory.getRole() == null) {
            return R.error("参数不完整");
        }
        chatHistoryService.saveChatHistory(chatHistory);
        return R.ok();
    }

    /**
     * 重命名会话
     */
    @PostMapping("/rename/{sessionId}")
    @RequiresPermissions("doc:chat:update")
    public R rename(@PathVariable("sessionId") String sessionId, @RequestBody Map<String, String> params) {
        String title = params.get("title");
        if (sessionId == null || sessionId.trim().isEmpty()) {
            return R.error("会话ID不能为空");
        }
        if (title == null || title.trim().isEmpty()) {
            return R.error("标题不能为空");
        }
        chatHistoryService.renameSession(sessionId, title);
        return R.ok();
    }

    /**
     * 更新向量嵌入
     */
    @PostMapping("/vector/{id}")
    @RequiresPermissions("doc:chat:update")
    public R updateVector(@PathVariable("id") Long id, @RequestBody Double[] vectorEmbedding){
        chatHistoryService.updateVectorEmbedding(id, vectorEmbedding);
        return R.ok();
    }

    /**
     * 删除会话
     */
    @PostMapping("/delete/{sessionId}")
    @RequiresPermissions("doc:chat:delete")
    public R delete(@PathVariable("sessionId") String sessionId){
        if (sessionId == null || sessionId.trim().isEmpty()) {
            return R.error("会话ID不能为空");
        }
        chatHistoryService.deleteSession(sessionId);
        return R.ok();
    }
}
